import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/import_wallet_page.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_language/lib_language.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/utils/utils.dart';
import 'package:lottie/lottie.dart';
import '../../../module_common/animate/fade_in_down_animation.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/routers.dart';
import '../../../module_common/utils/auth.dart';
import '../../../module_common/widgets/button/public_button.dart';
import '../../../module_common/widgets/dialog/password_auth_dialog.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../../module_create_wallet/widgets/password.dart';

class WalletLoginPage extends StatefulWidget {
  const WalletLoginPage({super.key});

  @override
  State<WalletLoginPage> createState() => _WalletIndexPageState();
}

class _WalletIndexPageState extends State<WalletLoginPage> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late final AnimationController lottieController;
  bool biometricLogin = false;
  bool goingHome = false;
  String password1 = '';
  bool showPassword1 = false;
  bool _isNodeVisible = false;
  bool _isNodeVisible2 = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    lottieController = AnimationController(vsync: this);
    _delayedShow();

    Authentication().canCheckBiometric().then((canCheckBiometric) {
      if (canCheckBiometric) {
        _goBiometric();
      }
    }).onError((error, stackTrace) {
      print(error);
      _goShowPassWord();
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      // 应用程序进入前台
      resetAnimalForward();
    }
  }

  @override
  void dispose() {
    lottieController.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _delayedShow() async {
    try {
      await Future.delayed(Duration(milliseconds: 500));
      if (mounted)
        setState(() {
          _isNodeVisible = true;
        });
      await Future.delayed(Duration(milliseconds: 300));
      if (mounted)
        setState(() {
          _isNodeVisible2 = true;
        });
    } catch (e) {
      print('error: $e');
    }
  }

  void resetAnimalForward() async {
    try {
      if (mounted)
        setState(() {
          _isNodeVisible = false;
          _isNodeVisible2 = false;
        });
      lottieController
        ..reset()
        ..forward();
      await Future.delayed(Duration(milliseconds: 300));
      if (mounted)
        setState(() {
          _isNodeVisible = true;
        });
      await Future.delayed(Duration(milliseconds: 300));
      if (mounted)
        setState(() {
          _isNodeVisible2 = true;
        });
    } catch (e) {
      print('error: $e');
    }
  }

  _goBiometric() {
    Authentication().startBiometricOnlyAuth().then((value) async {
      if (value) {
        await context.read<WalletInfoNotifier>();
        _goHome();
      }
    }).onError((error, stackTrace) {
      if (error is PlatformException) {
        if (error.code == 'NotAvailable') {
          Toast.show(context,
              status: '2',
              position: Dpositon.top,
              message: LocaleKeys.weiqiyongsuoxudeanquangongneng.tr(),
              duration: Duration(milliseconds: 3000));
        } else if (Utils.isNotEmpty(error.message)) {
          Toast.show(context,
              status: '2', message: error.message, position: Dpositon.top, duration: Duration(milliseconds: 3000));
        }
      } else {
        Toast.show(context,
            status: '2', position: Dpositon.top, message: error.toString(), duration: Duration(milliseconds: 3000));
      }
      _goShowPassWord();
    });
  }

  _goLogin() async {
    if (Utils.isEmpty(password1)) {
      Toast.show(context,
          status: '2', position: Dpositon.top, message: 'Invalid Password', duration: Duration(milliseconds: 3000));
      return;
    }

    if (!Authentication().validPassword(password1)) {
      Toast.show(context,
          status: '2', position: Dpositon.top, message: 'Invalid Password', duration: Duration(milliseconds: 3000));
      return;
    }
    await context.read<WalletInfoNotifier>();
    _goHome();
  }

  _goShowPassWord() async {
    dynamic result = await Utils.showBottomSheetDialog(
        context,
        PasswordAuthDialog(
          title: LocaleKeys.qingquerenqianbaomima.tr(),
        ));
    if (null != result && result is String && Utils.isNotEmpty(result)) {
      setState(() {
        password1 = result;
      });
    }
  }

  _goHome() {
    setState(() {
      goingHome = true;
    });
    Navigator.pushNamedAndRemoveUntil(
      context,
      Routes.rootAssetsPage, // 要跳转的新路由名称
      (route) => false, // 移除所有路由记录
    );
  }

  Widget generatePasswordWidget(String pwd) {
    List<Widget> widgets = [];
    for (var i = 0; i < pwd.length; i++) {
      widgets.add( Padding(
        padding: EdgeInsets.only(right: 4.w),
        child: DecoratedBox(
          decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.black),
          child: SizedBox(
            width: 8.w,
            height: 8.w,
          ),
        ),
      ));
    }
    return Row(
      children: widgets,
    );
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Scaffold(
        body: SingleChildScrollView(
      child: Column(
        children: [
          SizedBox(
            height: statusBarHeight,
          ),
          Container(
            padding: EdgeInsets.only(left: 20.w, top: 9.w, bottom: 9.w),
            alignment: Alignment.topLeft,
            height: 45.w,
            child: PublicImage(
              image: 'assets/images/create_wallet/logo.png',
              width: 54.w,
              height: 27.w,
            ),
          ),
          GestureDetector(
            onTap: () {
              lottieController
                ..reset()
                ..forward();
              // lottieController.forward();
            },
            child: Container(
              height: 300.w,
              alignment: Alignment.center,
              child: Lottie.asset(
                'assets/svg_json/empty_wallet.json',
                controller: lottieController,
                fit: BoxFit.contain,
                repeat: false,
                onLoaded: (composition) {
                  // Configure the AnimationController with the duration of the
                  // Lottie file and start the animation.
                  lottieController
                    ..duration = composition.duration
                    ..forward();
                },
              ),
            ),
          ),
          Container(
            height: 122.w,
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.topLeft,
                  child: _isNodeVisible
                      ? FadeInDownAnimation(
                          duration: Duration(milliseconds: 500),
                          child: Text(
                            'Welcome Back',
                            softWrap: true,
                            overflow: TextOverflow.visible,
                            style: TextStyle(
                                fontSize: 26.sp,
                                height: 37.w / 26.w,
                                fontWeight: FontWeight.w600,
                                color: Color.fromRGBO(51, 51, 51, 1)),
                          ))
                      : null,
                ),
                Container(
                    alignment: Alignment.topLeft,
                    child: _isNodeVisible2
                        ? FadeInDownAnimation(
                            duration: Duration(milliseconds: 500),
                            child: Text(
                              'Take you into the era of decentralization',
                              softWrap: true,
                              overflow: TextOverflow.visible,
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  height: 16.w / 12.w,
                                  fontWeight: FontWeight.w500,
                                  color: Color.fromRGBO(134, 131, 145, 1)),
                            ))
                        : null),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(
              left: 20,
            ),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Password',
                style: TextStyle(
                    color: Color.fromRGBO(51, 51, 51, 1),
                    height: 20.w / 14.w,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500),
              ),
            ),
          ),
          Container(
            width: double.infinity,
            padding:  EdgeInsets.only(left: 15.w, right: 15.w),
            height: 50.w,
            margin:  EdgeInsets.only(top: 10.w, left: 20.w, right: 20.w),
            decoration: BoxDecoration(color: Color.fromRGBO(246, 246, 246, 1), borderRadius: BorderRadius.circular(10)),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        _goShowPassWord();
                      },
                      child: Utils.isEmpty(password1)
                          ? Text(
                              'Enter your Password',
                              style: TextStyle(
                                  height: 20.w / 14.w,
                                  fontWeight: FontWeight.w400,
                                  fontSize: 14.sp,
                                  color: Color.fromRGBO(190, 189, 202, 1)),
                            )
                          : GeneratePassword.generatePasswordWidget(password1, showPassword1)),
                ),
                Visibility(
                    visible: true,
                    child: GestureDetector(
                      onTap: () {
                        _goBiometric();
                      },
                      child: Platform.isIOS
                          ? PublicImage(
                              image: 'assets/images/create_wallet/faceid.png',
                              width: 20.w,
                              height:20.w,
                            )
                          : PublicImage(
                              image: 'assets/images/create_wallet/fingerprint.png',
                              width: 20.w,
                              height: 20.w,
                            ),
                    ))
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (context) => ImportWalletPage(type: ImportWalletPageType.ResetPassword)))
                  .then((value) {
                resetAnimalForward();
              });
            },
            child: Container(
              padding: EdgeInsets.only(left: 20.w, top: 10.w),
              alignment: Alignment.centerLeft,
              child: Text(
                'Forgot Password?',
                style: TextStyle(
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    height: 17.w / 12.w,
                    color: Color.fromRGBO(134, 104, 254, 1)),
              ),
            ),
          ),
           SizedBox(
            height: 40.w,
          ),
          PublicButton(
              radius:10.w,
              height: 46.w,
              disabledStatus: password1.length <= 0,
              type: ButtonType.private,
              text: 'Log in',
              onClick: goingHome
                  ? null
                  : () {
                      if (password1.length > 0) _goLogin();
                    }),
           SizedBox(
            height: 30.w,
          ),
        ],
      ),
    ));
  }
}
